import { Form, Toast } from 'antd-mobile'
import { asyncgetToken } from '@/store/actions/login'
import { useDispatch } from 'react-redux'
import { loginFormdata } from '@/types/data'
import { AppDispatch } from '@/store'
import { useNavigate } from 'react-router-dom'
import { AxiosError } from 'axios'
import { useEffect, useRef, useState } from 'react'
import { InputRef } from 'antd-mobile/es/components/input'
import { send } from '@/api/user'
export function useLogin() {
  const dis = useDispatch<AppDispatch>()
  const nav = useNavigate()
  const [form] = Form.useForm()
  const mobileRef = useRef<InputRef>(null)
  const [time, settime] = useState(0)
  const onFinish = async (formData: loginFormdata) => {
    console.log('formData:', formData)
    try {
      await dis(asyncgetToken(formData))
      Toast.show({
        icon: 'success',
        content: '登录成功',
      })
      nav('/')
    } catch (error) {
      // console.log(error.response.data.message)
      const _error = error as AxiosError<{ message: string }>
      Toast.show({
        icon: 'fail',
        content: _error.response?.data.message,
      })
    }
  }
  const timeId = useRef(0)
  const sendCode = async () => {
    // 拿到手机号
    const mobile = (form.getFieldValue('mobile') ?? '') as string
    const hasError = form.getFieldError('mobile').length > 0
    if (hasError || mobile.trim() === '') {
      Toast.show({
        icon: 'fail',
        content: '手机号格式错误',
      })
      return mobileRef.current?.focus()
    }
    try {
      await send(mobile)
      Toast.show({
        icon: 'success',
        content: '验证码发送成功',
      })
      settime(60)
      timeId.current = window.setInterval(() => {
        settime((time) => time - 1)
      }, 1000)
    } catch (error) { }
  }
  useEffect(() => {
    if (time === 0) {
      console.log('时间到定时器销毁')
      clearInterval(timeId.current)
    }
  }, [time])
  useEffect(() => {
    return () => {
      console.log('时跳页面定时器销毁')
      clearInterval(timeId.current)
    }
  }, [])
  return { form, onFinish, mobileRef, time, sendCode }
}


